package com.youlai.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.form.LocationForm;
import com.youlai.system.model.query.LocationPageQuery;
import com.youlai.system.model.vo.LocationPageVO;
import com.youlai.system.model.vo.LocationScoreCountVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.SysLocationService;
import com.youlai.system.service.SysScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 培训地点控制器
 */
@Tag(name = "10.培训地点接口")
@RestController
@RequestMapping("/api/v1/locations")
@RequiredArgsConstructor
public class SysLocationController {

    private final SysLocationService locationService;

    private final SysScoreService scoreService;

    @Operation(summary = "培训地点分页列表")
    @GetMapping("/page")
    public PageResult<LocationPageVO> getLocationPage(
            @ParameterObject LocationPageQuery queryParams
    ) {
        IPage<LocationPageVO> result = locationService.getLocationPage(queryParams);
        Map<Long, LocationScoreCountVO> locationScoreCountMap = scoreService.getAllLocationScoreCountMap();
        result.getRecords().forEach(locationPageVO -> {
            LocationScoreCountVO locationScoreCountVO = locationScoreCountMap.get(locationPageVO.getId());
            if (locationScoreCountVO != null) {
                locationPageVO.setTotalCount(locationScoreCountVO.getTotalCount());
                locationPageVO.setSuccessCount(locationScoreCountVO.getSuccessCount());
                locationPageVO.setFailCount(locationScoreCountVO.getFailCount());
                locationPageVO.setSuccessRate(locationScoreCountVO.getSuccessRate());
            }
        });
        return PageResult.success(result);
    }

    @Operation(summary = "新增培训地点")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:location:add')")
    @PreventDuplicateSubmit
    public Result saveLocation(
            @RequestBody @Valid LocationForm locationForm
    ) {
        boolean result = locationService.saveLocation(locationForm);
        return Result.judge(result);
    }

    @Operation(summary = "培训地点表单数据")
    @GetMapping("/{locationId}/form")
    public Result<LocationForm> getLocationForm(
            @Parameter(description = "培训地点ID") @PathVariable Long locationId
    ) {
        LocationForm formData = locationService.getLocationForm(locationId);
        return Result.success(formData);
    }


    @Operation(summary = "修改培训地点")
    @PutMapping(value = "/{locationId}")
    @PreAuthorize("@ss.hasPerm('sys:location:edit')")
    public Result updateLocation(
            @Parameter(description = "培训地点ID") @PathVariable Long locationId,
            @RequestBody @Validated LocationForm locationForm) {
        boolean result = locationService.updateLocation(locationId, locationForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除培训地点")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:location:delete')")
    public Result deleteLocations(
            @Parameter(description = "培训地点ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "培训地点删除数据为空");
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean locationHasUsed = scoreService.locationHasUsed(idList);
        Assert.isTrue(!locationHasUsed, "培训地点使用中，不能被删除");
        boolean result = locationService.deleteLocations(idList);
        return Result.judge(result);
    }

    @Operation(summary = "培训地点下拉列表")
    @GetMapping("/options")
    public Result<List<Option>> listCategoryOptions() {
        List<Option> list = locationService.listLocationOptions();
        return Result.success(list);
    }

}
